<?php

declare(strict_types=1);


namespace App\Utils\Upload;


use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use Hyperf\HttpMessage\Upload\UploadedFile;

class Validator
{
    public $allowMine = [
        'image/jpg',
        'image/jpeg',
        'image/gif',
        'image/wbmp',
        'image/png'
    ];

    public $allowSize = 1024 * 1024 * 2;

    public $allowSuffix = [
        'jpg',
        'jpeg',
        'gif',
        'wbmp',
        'png'

    ];

    public function __construct(array $allowOptions = [])
    {
        if ($allowOptions) {
            $this->setAllowOptions($allowOptions);
        }
    }

    public function validated(UploadedFile $file): bool
    {
        if ($file->getSize() > $this->allowSize) {
            throw new BusinessException(ErrorCode::UPLOAD_SIZE_LIMIT);
        }

        if (!in_array($file->getMimeType(), $this->allowMine)) {
            throw new BusinessException(ErrorCode::UPLOAD_MIME_LIMIT);
        }

        if (!in_array($file->getExtension(), $this->allowSuffix)) {
            throw new BusinessException(ErrorCode::UPLOAD_SUFFIX_LIMIT);
        }
        return true;
    }

    public function setAllowOptions(array $allowOptions)
    {
        foreach ($allowOptions as $key => $value) {
            property_exists(self::class, $key) && $this->{$key} = $value;
        }
    }
}